package ice.server.comm;

import ice.tool.GsonUtil;
import ice.tool.PageVO;
import ice.tool.validation.StringValidator;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.microdream.easy.deploy.po.DOrg;
import org.microdream.easy.deploy.po.DUser;
import org.microdream.easy.deploy.po.DUserOrg;
import org.microdream.easy.deploy.service.DOrgService;
import org.microdream.easy.deploy.service.DUserOrgService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

public class BaseAction {
	
	/**
	 * 这样写并不会导致线程安全问题
	 */
	@Resource
	private HttpServletRequest req;
	
	/**
	 * 这样写并不会导致线程安全问题
	 */
	@Resource
	private HttpServletResponse resp;

	@Resource
	private DUserOrgService dUserOrgService;

	@Resource
	private DOrgService dOrgService;
	
	private Logger log = LoggerFactory.getLogger(BaseAction.class);
	
	public int getRows() {
		try {
			int rows = Integer.valueOf(req.getParameter("limit"));
			return rows;
		} catch(Exception e) {
			log.error("未设置rows");
		}
		return -1;
	}
	
	public int getPage() {
		try {
			int offset = Integer.valueOf(req.getParameter("offset"));
			return offset / getRows();
		} catch(Exception e) {
			log.error("未设置page");
		}
		return -1;
	}
	
	public void outBack(String data, String type) {
		resp.setCharacterEncoding("utf-8");
		resp.setContentType(type);
		try {
			resp.getWriter().print(data);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public <T> PageVO<T> pageToVO(Page<T> p) {
		PageVO<T> vp = new PageVO<T>();
		vp.setContentList(p.getContent());
		vp.setCurrPage(p.getNumber());
		vp.setTotalPages(p.getTotalPages());
		vp.setTotals(p.getTotalElements());
		return vp;
	}
	
	public <T> ResultPage<T> pageToResultPage(Page<T> p) {
		ResultPage<T> rp = new ResultPage<>();
		rp.setPage(p.getNumber());
		rp.setTotal(p.getTotalElements());
		rp.setRows(p.getContent());
		return rp;
	}
	
	public int getIntParam(String param) throws Exception{
		String p = req.getParameter(param);
		if(StringValidator.isEmpty(p)) {
			throw new NumberFormatException("参数为空，无法转为int类型");
		}
		return Integer.parseInt(p);
	}
	
	public String getStringParam(String param) {
		String p = req.getParameter(param);
		if(StringValidator.isEmpty(p)) {
			return "";
		}
		return p.trim();
	}
	
	/**
	 * 构造ajax回写的 字符串
	 * @param success
	 * @param msg
	 * @return
	 */
	protected String getFeedJson(String success, String msg) {
		Map<String, String> map = new HashMap<String, String>();
		map.put("success", success);
		map.put("msg", msg);
		String json = GsonUtil.ObjToString(map, null);
		return json;
	}
	
	/**
	 * 获取当前登录账户
	 * @return
	 */
	public String getMyAccount() {
		// TODO:
		return "superadmin";
	}
	
	
	/**
	 * 获取当前登录用户姓名
	 * @return
	 */
	public String getMyName() {
		// TODO:
		return "superadmin";
	}

	/**
	* 功能描述:〈获取当前登录用户〉
	* @param
	* @return : org.microdream.easy.deploy.po.DUser
	* @author : 沈明可
	* @date : 2019/9/15 20:20
	* User :
	*/
	public DUser getCurrentLoggedInUser(){
		DUser dUser = new DUser();
		return  dUser;
	}

	/**
	* 功能描述:〈获取当前登录用户所属机构〉
	* @param
	* @return : java.util.List<org.microdream.easy.deploy.po.DOrg>
	* @author : 沈明可
	* @date : 2019/9/15 20:45
	* User :
	*/
	public List<DOrg> getMechanism(){
        DUser currentLoggedInUser = getCurrentLoggedInUser();
        List<DUserOrg> userOrgS = dUserOrgService.find(ParamBulider.build().add("userAccount", currentLoggedInUser.getId()).get());
		List<String> collect = userOrgS.stream().map(dUserOrg -> dUserOrg.getOrgCode()).collect(Collectors.toList());
		List<DOrg> all = dOrgService.findAll();
		if(currentLoggedInUser.getIsGod().equals(1)){
		    return  all;
        }
        List<DOrg> collect1 = all.stream().filter(dOrg -> collect.contains(dOrg.getOrgCode())).collect(Collectors.toList());
        collect1.forEach(dOrg -> {
            List<DOrg> dOrgs = formatMechanism(all, dOrg.getOrgCode());
            if(CollectionUtils.isNotEmpty(dOrgs)){
                collect1.addAll(dOrgs);
            }
        });
		HashSet<DOrg> dOrgs =  new HashSet<>(collect1);
		collect1.clear();
		collect1.addAll(dOrgs);
        return  collect1;
    }

    /**
    * 功能描述:〈获取当前机构下属子机构〉
    * @param all 所有机构
     * @param code 当前机构编码
    * @return : java.util.List<org.microdream.easy.deploy.po.DOrg>
    * @author : 沈明可
    * @date : 2019/9/15 20:46
    * User :
    */
	public List<DOrg> formatMechanism(List<DOrg> all,String code){
        List<DOrg> dOrgS =  new ArrayList<>();
		for(int i= 0;i<all.size();i++){
            DOrg dOrg = all.get(i);
            if(dOrg.getOrgCode().equals(code)){
                dOrgS.add(dOrg);
                List<DOrg> dOrgs = formatMechanism(all, dOrg.getOrgCode());
                if(CollectionUtils.isNotEmpty(dOrgs)){
                    dOrgS.addAll(dOrgs);
                }
            }
		}
		return dOrgS;
	}

}
